package com.sheng.leetcode.year2024.month02.day26;

import org.junit.Test;

/**
 * @author by ls
 * @date 2024/2/26
 * <p>
 * 938. 二叉搜索树的范围和<p>
 * <p>
 * 给定二叉搜索树的根结点 root，返回值位于范围 [low, high] 之间的所有结点的值的和。<p>
 * <p>
 * 示例 1：<p>
 * 输入：root = [10,5,15,3,7,null,18], low = 7, high = 15<p>
 * 输出：32<p>
 * <p>
 * 示例 2：<p>
 * 输入：root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10<p>
 * 输出：23<p>
 * <p>
 * 提示：<p>
 * 树中节点数目在范围 [1, 2 * 10^4] 内<p>
 * 1 <= Node.val <= 10^5<p>
 * 1 <= low <= high <= 10^5<p>
 * 所有 Node.val 互不相同<p>
 */
public class LeetCode0938 {

    @Test
    public void test01() {
//        TreeNode root = new TreeNode(10, new TreeNode(5, new TreeNode(3), new TreeNode(7)), new TreeNode(15, null, new TreeNode(18)));
//        int low = 7, high = 15;
        TreeNode root = new TreeNode(10, new TreeNode(5, new TreeNode(3, new TreeNode(1), null), new TreeNode(7, new TreeNode(6), null)), new TreeNode(15, new TreeNode(13), new TreeNode(18)));
        int low = 6, high = 10;
        System.out.println(new Solution().rangeSumBST(root, low, high));
    }
}

class Solution {

    int low, high, ans;

    public int rangeSumBST(TreeNode root, int low, int high) {
        this.low = low;
        this.high = high;
        ans = 0;
        dfs(root);
        return ans;
    }

    public void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.val <= high && root.val >= low) {
            ans += root.val;
        }
        dfs(root.left);
        dfs(root.right);
    }
}

// Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
